//获取某个元素，到顶部的距离
export function offset(obj) {
  let item = {
    top: obj.offsetTop,  //到父元素的距离
    left: obj.offsetLeft
  };
  
  while(obj.offsetParent) {
    obj = obj.offsetParent;
    item.left += obj.offsetLeft;
    item.top += obj.offsetTop;
  }
  return item;
}

//获取当前位置
export function getPosition() {
  if (window.pageYOffset != null) {
    return {
      left: window.pageXOffset,   
      top: window.pageYOffset,
    };
  } else if (document.compatMode == "CSS1Compat") {
    return {
      left: document.documentElement.scrollLeft,
      top: document.documentElement.scrollTop,
    };
  }
  return {
    left: document.body.scrollLeft,
    top: document.body.scrollTop,
  };
}


export let scroll_to_top_timer=0;

//滚动动画
export function toScoll(items, index) {
  const targetElement = items[index];
  if (!targetElement) return;

  const targetPosition = offset(targetElement).top;
  const startPosition = window.pageYOffset;
  const distance = targetPosition - startPosition;
  const duration = 500; // 动画持续时间（ms）
  let startTime = null;

  function animation(currentTime) {
    if (!startTime) startTime = currentTime;
    const timeElapsed = currentTime - startTime;
    const progress = Math.min(timeElapsed / duration, 1);
    
    // 使用缓动函数让滚动更平滑
    const easeInOutQuad = t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    const scrollPosition = startPosition + distance * easeInOutQuad(progress);
    
    window.scrollTo(0, scrollPosition);

    if (progress < 1) {
      requestAnimationFrame(animation);
    }
  }

  requestAnimationFrame(animation);
}